//
//  LoginPageVC.m
//  GasCome
//
//  Created by zfc on 2020/4/20.
//  Copyright © 2020 zfc. All rights reserved.
//

#import "LoginVC.h"
//#import "RegisterVC.h"
#import "ForgetPwdVC.h"
//#import "WxBindPhoneVC.h"
#import <AuthenticationServices/AuthenticationServices.h>

@interface LoginVC () <UITextFieldDelegate, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding, WXApiDelegate>

@property (nonatomic, assign) BOOL isCodeLogin;
@property (nonatomic, strong) UITextField *phoneTf;
@property (nonatomic, strong) UITextField *pwdTf;
@property (nonatomic, strong) UITextField *codeTf;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong)dispatch_source_t timer;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];


    self.fd_prefersNavigationBarHidden = YES;
    self.fd_interactivePopDisabled = YES;

    [self setUI];


    [self.phoneTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.pwdTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.codeTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxLoginResult:) name:@"wxLogin" object:nil];

}

- (void) setUI {

    self.view.backgroundColor = WhiteColor;
    UIImageView *logoImgV = [[UIImageView alloc] init];
    logoImgV.image =  [UIImage imageNamed:@"register_ic_logo"];
    [self.view addSubview:logoImgV];
    [logoImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(30+kTopHeight);
    }];

    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage: [UIImage imageNamed:@"common_ic_close"] forState:UIControlStateNormal];
    [cancelBtn setImage:[UIImage imageNamed:@"common_ic_close"] forState:UIControlStateHighlighted];

    [self.view addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(15);
        make.top.equalTo(self.view).offset(10+kToolHeight);
    }];
    WeakSelf;
    cancelBtn.block = ^(UIButton *sender) {
        [weakSelf.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    };

//    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
//    registBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
//    [registBtn setTitleColor: BlackColor forState:UIControlStateNormal];
//    [self.view addSubview:registBtn];
//    [registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.trailing.equalTo(self.view).offset(-15);
//        make.top.equalTo(self.view).offset(10+kToolHeight);
//    }];
//
//    registBtn.block = ^(UIButton *sender) {
//        RegisterVC *vc = [[RegisterVC alloc] init];
//        [weakSelf.navigationController pushViewController:vc animated:YES];
//    };

    //手机号视图
    UIView *phoneView = [[UIView alloc] init];
    [self.view addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(logoImgV.mas_bottom).offset(6);
        make.height.mas_equalTo(60);
    }];

    UIImageView *phoneImgV = [[UIImageView alloc] init];
    phoneImgV.image = [UIImage imageNamed:@"register_ic_phone"];
    [phoneView addSubview:phoneImgV];
    [phoneImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(phoneView);
        make.leading.equalTo(phoneView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *phoneTf = [[UITextField alloc] init];
    NSAttributedString *phoneAttr = [[NSAttributedString alloc] initWithString:@"请输入登录手机号" attributes:
    @{NSForegroundColorAttributeName:Color999,
      NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];

//    NSAttributedString *phoneIsSaleManAttr = [[NSAttributedString alloc] initWithString:@"请输入登录手机号" attributes:
//    @{NSForegroundColorAttributeName:gcColorB1B9C0,
//      NSFontAttributeName:[UIFont systemFontOfSize:14]
//    }];
    phoneTf.attributedPlaceholder = phoneAttr;
    phoneTf.textColor = BlackColor;
    phoneTf.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTf];
    self.phoneTf = phoneTf;
    [phoneTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(phoneView).offset(44);
        make.centerY.equalTo(phoneView);
        make.trailing.equalTo(phoneView).offset(-10);
    }];

    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = ColorE6;
    [phoneView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(phoneView);
        make.height.mas_equalTo(0.5);
    }];


    //密码视图
    UIView *pwdView = [[UIView alloc] init];
    pwdView.hidden = self.isCodeLogin;

    [self.view addSubview:pwdView];
    [pwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(phoneView.mas_bottom);
        make.height.mas_equalTo(60);
    }];

    UIImageView *pwdImgV = [[UIImageView alloc] init];
    pwdImgV.image = [UIImage imageNamed:@"register_ic_password"];
    [pwdView addSubview:pwdImgV];
    [pwdImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(pwdView);
        make.leading.equalTo(pwdView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *pwdTf = [[UITextField alloc] init];
    NSAttributedString *pwdAttr = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:
    @{NSForegroundColorAttributeName:Color999,
      NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];


    pwdTf.attributedPlaceholder = pwdAttr;
    pwdTf.textColor = BlackColor;
    pwdTf.delegate = self;
    pwdTf.secureTextEntry = YES;
    [pwdView addSubview:pwdTf];
    self.pwdTf = pwdTf;
    [pwdTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(pwdView).offset(44);
        make.centerY.equalTo(pwdView);
        make.trailing.equalTo(pwdView).offset(-50);
    }];


    UIButton *eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [eyeBtn setImage:[UIImage imageNamed:@"denglu_ic_eye opened"] forState:UIControlStateNormal];
    [eyeBtn setImage:[UIImage imageNamed:@"denglu_ic_eye closed"] forState:UIControlStateSelected];
    eyeBtn.selected = YES;
    eyeBtn.block = ^(UIButton *sender) {
        sender.selected = !sender.selected;
        pwdTf.secureTextEntry = sender.selected;
    };
    [pwdView addSubview:eyeBtn];
    [eyeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(pwdView);
        make.width.height.mas_equalTo(20);
        make.trailing.equalTo(pwdView).offset(-10);
    }];


    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = ColorE6;
    [pwdView addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(pwdView);
        make.height.mas_equalTo(0.5);
    }];


    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    loginBtn.cornerRadius = 8;
    loginBtn.backgroundColor = [UIColor bm_colorGradientChangeWithSize:CGSizeMake(kScreenW-140, 50) direction:IHGradientChangeDirectionLevel startColor:[UIColor colorWithHexString:@"F74040"] endColor:[UIColor colorWithHexString:@"FAC966"]];
    [self.view addSubview:loginBtn];
    self.loginBtn = loginBtn;
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneView.mas_bottom).offset(110);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.leading.equalTo(self.view).offset(70);
    }];

    loginBtn.block = ^(UIButton *sender) {
        //登录成功 发送通知
        [weakSelf login];
    };

    UIView *loginBottomView = [[UIView alloc] init];
    [self.view addSubview:loginBottomView];
    [loginBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(60);
        make.top.equalTo(loginBtn.mas_bottom);
    }];


/*
    UIButton *cutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cutBtn setImage:self.isSalesMan ? [UIImage imageNamed:@"register_ic_switch2"] : [UIImage imageNamed:@"register_ic_switch"] forState:UIControlStateNormal];
    [cutBtn setImage:self.isSalesMan ? [UIImage imageNamed:@"register_ic_switch2"] : [UIImage imageNamed:@"register_ic_switch"] forState:UIControlStateHighlighted];
    [self.view addSubview:cutBtn];
    [cutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-kBottomWhiteHeight);
    }];
    cutBtn.block = ^(UIButton *sender) {
        StrongSelf;
        CATransition *animation1 = [CATransition animation];//类方法创建一个切换对象
            animation1.duration = 0.45;//动画持续时间
            animation1.type = @"pageCurl";//动画效果

        [strongSelf.navigationController.view.layer addAnimation:animation1 forKey:nil];//加载动画到导航控制器的layer层
        LoginVC *vc = [[LoginVC alloc] init];
        vc.isSalesMan = !strongSelf.isSalesMan;
        [strongSelf.navigationController pushViewController:vc animated:NO];
    };

    if (self.isSalesMan) {
//        pwdView.hidden = NO;
        return;
    }

    */

    //验证码视图
    UIView *codeView = [[UIView alloc] init];
    codeView.hidden = !self.isCodeLogin;
    [self.view addSubview:codeView];
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(phoneView.mas_bottom);
        make.height.mas_equalTo(60);
    }];

    UIImageView *codeImgV = [[UIImageView alloc] init];
    codeImgV.image = [UIImage imageNamed:@"register_ic_code"];
    [codeView addSubview:codeImgV];
    [codeImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(codeView);
        make.leading.equalTo(codeView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *codeTf = [[UITextField alloc] init];
    NSAttributedString *codeAttr = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:
    @{NSForegroundColorAttributeName:Color999,
      NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];

    codeTf.attributedPlaceholder = codeAttr;
    codeTf.keyboardType = UIKeyboardTypeNumberPad;
    [codeView addSubview:codeTf];
    self.codeTf = codeTf;
    [codeTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(codeImgV.mas_trailing).offset(20);
        make.centerY.equalTo(codeView);
        make.trailing.equalTo(codeView).offset(-90);
    }];

    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [codeBtn setTitle:@"  发送验证码  " forState:UIControlStateNormal];
    [codeBtn setTitleColor:Color333 forState:UIControlStateNormal];
    codeBtn.titleLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
    codeBtn.cornerRadius = 1.5;
    codeBtn.borderColor = Color999;
    codeBtn.borderWidth = 0.5;
    [codeView addSubview:codeBtn];
    [codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(28);
        make.centerY.equalTo(codeView);
        make.trailing.equalTo(codeView);
    }];
    codeBtn.block = ^(UIButton *sender) {
        //点击发送验证码
        [weakSelf actionGetCode:sender];

    };

    UIView *lineView2 = [[UIView alloc] init];
    lineView2.backgroundColor = ColorE6;
    [codeView addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(codeView);
        make.height.mas_equalTo(0.5);
    }];

    UIButton *codeLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [codeLoginBtn setTitle:self.isCodeLogin ? @"密码登录":@"短信验证码登录" forState:UIControlStateNormal];
    codeLoginBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [codeLoginBtn setTitleColor: Color999 forState:UIControlStateNormal];
    [loginBottomView addSubview:codeLoginBtn];
    [codeLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(loginBottomView);
        make.leading.equalTo(loginBottomView);
    }];
    codeLoginBtn.block = ^(UIButton *sender) {
        StrongSelf;
        strongSelf.isCodeLogin = !strongSelf.isCodeLogin;
        pwdView.hidden = strongSelf.isCodeLogin;
        codeView.hidden = !strongSelf.isCodeLogin;
        [sender setTitle:strongSelf.isCodeLogin ? @"密码登录":@"短信验证码登录" forState:UIControlStateNormal];
    };

    UIView *lineView3 = [[UIView alloc] init];
    lineView3.backgroundColor =  ColorE6;
    [loginBottomView addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(loginBottomView);
        make.width.mas_equalTo(0.5);
        make.height.mas_equalTo(12);
        make.leading.equalTo(codeLoginBtn.mas_trailing).offset(10);
    }];

    UIButton *forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [forgetPwdBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
    forgetPwdBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [forgetPwdBtn setTitleColor: Color999 forState:UIControlStateNormal];
    [loginBottomView addSubview:forgetPwdBtn];
    [forgetPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(loginBottomView);
        make.leading.equalTo(lineView3.mas_trailing).offset(10);
        make.trailing.equalTo(loginBottomView);
    }];
    forgetPwdBtn.block = ^(UIButton *sender) {
        ForgetPwdVC *vc = [[ForgetPwdVC alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };


/*
    UIButton *wxBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [wxBtn setImage:[UIImage imageNamed:@"denglu_ic_weixin"] forState:UIControlStateNormal];
    [wxBtn setImage:[UIImage imageNamed:@"denglu_ic_weixin"] forState:UIControlStateHighlighted];
    [self.view addSubview:wxBtn];
    [wxBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-30-kBottomWhiteHeight);
    }];
    wxBtn.block = ^(UIButton *sender) {

         if ([WXApi isWXAppInstalled]) {
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = @"wx_oauth_authorization_state1";
            [WXApi sendReq:req completion:nil];
        }else{
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = @"wx_oauth_authorization_state1";
            [WXApi sendAuthReq:req viewController:weakSelf delegate:weakSelf completion:nil];
        }
//        SendAuthReq *req = [[SendAuthReq alloc] init];
//        req.scope = @"snsapi_userinfo";
//        req.state = @"wx_oauth_authorization_state1";
//        [WXApi sendReq:req completion:nil];

//        WxBindPhoneVC *vc = [[WxBindPhoneVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
    };

    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDButton *abtn = [ASAuthorizationAppleIDButton
                                              buttonWithType:ASAuthorizationAppleIDButtonTypeSignIn
                                              style:ASAuthorizationAppleIDButtonStyleBlack];

        [self.view addSubview:abtn];
        [abtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(wxBtn.mas_top).offset(-20);
        }];
        abtn.cornerRadius = 3;

        [abtn addTarget:self action:@selector(signInWithApple) forControlEvents:UIControlEventTouchUpInside];


    }

    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"—————— 第三方登录 ——————";
    lab.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
    lab.textColor =  ColorCC;
    [self.view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(wxBtn.mas_top).offset(-80);
    }];
*/
}



- (void) wxLoginResult:(NSNotification *)noti {
    NSDictionary *userInfoDic = noti.object;
    NSString *code = userInfoDic[@"code"];
    NSLog(@"微信登录成功userInfoDic:%@", userInfoDic);

    [self getWxPlatformDataWithCode:code];

}

//后台获取授权登录
- (void) getWxPlatformDataWithCode:(NSString *)code {
    [[NetWorksTools shared] requestWithNotTokenMethod:GET url:@"/api/tiny-shop/v1/third-party/wechat-open-platform" params:@{@"code":code} successBlock:^(NSDictionary * _Nonnull response) {

        NSDictionary *data = response[@"data"];
        if ([data[@"login"] intValue] == 1) { //登录信息


            //使用归档保存数据
            LoginModel *model = [LoginModel mj_objectWithKeyValues:data[@"user_info"]];
            [[UserAccountManager shared] saveUser:model];
//            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsSalesMan];
//            [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];


            [JPushFunc pushJPushRegisterID];
            [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        } else {//授权信息

//            WxBindPhoneVC *vc = [[WxBindPhoneVC alloc] init];
//            vc.authDic = data[@"user_info"];
//            vc.type = 0;
//            [self.navigationController pushViewController:vc animated:YES];
        }
    } failureBlock:^(NSError * _Nonnull error) {

    }];
}


- (void) login {

    [SVProgressHUD showWithStatus:@"正在登录"];
    self.loginBtn.enabled = NO;

    if (!self.isCodeLogin) {  //密码登录
        [self pwdLogin];
    } else {                  //验证码登录
        [self codeLogin];
    }
}

//密码登录
- (void) pwdLogin {
    BOOL isValid = [Untils cheackPhoneNumValid:self.phoneTf.text];
    if(!isValid){
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        self.loginBtn.enabled = YES;
        return;
    }

    if (self.pwdTf.text.length < 6 || self.pwdTf.text.length > 15) {
        [SVProgressHUD showInfoWithStatus:@"密码格式错误"];
        self.loginBtn.enabled = YES;
        return;
    }

    NSString *url = @"/tiny-shop/v1/site/login";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = self.phoneTf.text;
    params[@"password"] = self.pwdTf.text;
//    params[@"registration_id"] = [JPUSHService registrationID] ? [JPUSHService registrationID] : @"";
    params[@"registration_id"] = @"233";

    params[@"group"] = @"tinyShopApp";

    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:url params:params successBlock:^(NSDictionary * _Nonnull response) {
        [SVProgressHUD showInfoWithStatus:@"登录成功"];
        self.loginBtn.enabled = YES;


        //使用归档保存数据
        LoginModel *model = [LoginModel mj_objectWithKeyValues:response[@"data"]];
        [[UserAccountManager shared] saveUser:model];
//        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsSalesMan];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];

        //登录成功
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        [JPushFunc pushJPushRegisterID];

    } failureBlock:^(NSError * _Nonnull error) {
        self.loginBtn.enabled = YES;

        NSLog(@"error:%@", error.description);

    }];

}

//验证码登录
- (void) codeLogin {
    BOOL isValid = [Untils cheackPhoneNumValid:self.phoneTf.text];
    if(!isValid){
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        self.loginBtn.enabled = YES;
        return;
    }

    if (self.codeTf.text.length != 4) {
        [SVProgressHUD showInfoWithStatus:@"请输入4位手机验证码"];
        self.loginBtn.enabled = YES;
        return;
    }

    NSString *url = @"/tiny-shop/v1/site/mobile-login";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = self.phoneTf.text;
    params[@"code"] = self.codeTf.text;
    params[@"group"] = @"tinyShopApp";

    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:url params:params successBlock:^(NSDictionary * _Nonnull response) {
        [SVProgressHUD showInfoWithStatus:@"登录成功"];
        self.loginBtn.enabled = YES;


        //使用归档保存数据
        LoginModel *model = [LoginModel mj_objectWithKeyValues:response[@"data"]];
        [[UserAccountManager shared] saveUser:model];

        //登录成功
//        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsSalesMan];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];

        //登录成功
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        [JPushFunc pushJPushRegisterID];
    } failureBlock:^(NSError * _Nonnull error) {
        self.loginBtn.enabled = YES;

    }];
}

//业务端登录
- (void)SalesManLogin {
    //别忘记
//    [SVProgressHUD showInfoWithStatus:@"登录成功"];
//    self.loginBtn.enabled = YES;

    BOOL isValid = [Untils cheackPhoneNumValid:self.phoneTf.text];
    if(!isValid){
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        self.loginBtn.enabled = YES;
        return;
    }

    if (self.pwdTf.text.length < 6 || self.pwdTf.text.length > 15) {
        [SVProgressHUD showInfoWithStatus:@"密码格式错误"];
        self.loginBtn.enabled = YES;
        return;
    }

    NSString *url = @"/merapi/v1/site/login";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"username"] = self.phoneTf.text;
    params[@"password"] = self.pwdTf.text;
//    params[@"registration_id"] = [JPUSHService registrationID] ? [JPUSHService registrationID] : @"";
    params[@"registration_id"] = [JPUSHService registrationID] ? [JPUSHService registrationID] : @"";

    params[@"group"] = @"ios";
    params[@"type"] = @"1";
    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:url params:params successBlock:^(NSDictionary * _Nonnull response) {
        [SVProgressHUD showInfoWithStatus:@"登录成功"];
        self.loginBtn.enabled = YES;


        //登录成功
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsSalesMan];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];

        //使用归档保存数据
        LoginModel *model = [LoginModel mj_objectWithKeyValues:response[@"data"]];
        [[UserAccountManager shared] saveUser:model];
//        [JPushFunc pushJPushRegisterID];


    } failureBlock:^(NSError * _Nonnull error) {
        self.loginBtn.enabled = YES;

    }];

}

- (void)actionGetCode:(id)sender {
    BOOL isValid = [Untils cheackPhoneNumValid:self.phoneTf.text];
    if(!isValid){
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        return;
    }

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = self.phoneTf.text;
    params[@"usage"] = @"login";

    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:@"/tiny-shop/v1/site/sms-code" params:params successBlock:^(NSDictionary * _Nonnull response) {

        NSLog(@"登录验证码: %@", response[@"data"]);
        //倒计时状态下的颜色
        [self setTheCountdownButton:sender startWithTime:59 title:@"重新获取"countDownTitle:@"s"mainColor:WhiteColor countColor:WhiteColor countTitleColor:Color999];
    } failureBlock:^(NSError * _Nonnull error) {

    }];
}


#pragma mark - button倒计时
- (void)setTheCountdownButton:(UIButton *)button startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(UIColor *)mColor countColor:(UIColor *)color countTitleColor:(UIColor *)titleColor{
    //倒计时时间
    NSInteger endTime = [[NSDate date] timeIntervalSince1970] + timeLine;
    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    //每秒执行一次
    dispatch_source_set_timer( self.timer,dispatch_walltime(NULL,0), 1.0 * NSEC_PER_SEC,0);
    WeakSelf;
    dispatch_source_set_event_handler( self.timer, ^{
        NSInteger currentTIme = [[NSDate date] timeIntervalSince1970];

        //倒计时结束，关闭
        if (endTime <= currentTIme) {
            dispatch_source_cancel( weakSelf.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                button.backgroundColor = mColor;
                [button setTitle:[NSString stringWithFormat:@"  %@  ", title] forState:UIControlStateNormal];
                button.userInteractionEnabled =YES;
            });
        } else {
            NSString *timeStr = [NSString stringWithFormat:@"  %@(%d%@)  ", title,endTime-currentTIme, subTitle];
            dispatch_async(dispatch_get_main_queue(), ^{
                button.backgroundColor = color;
                [button setTitleColor:titleColor forState:UIControlStateNormal];
                [button setTitle:timeStr forState:UIControlStateNormal];
                button.userInteractionEnabled = NO;
            });
        }
    });
    dispatch_resume( self.timer);
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@" "] || [Untils isChinese:string]) {
        return NO;
    } else {
        return YES;
    }
}

-(void)changedTextField:(UITextField *)textField {

    if (textField == self.phoneTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }

    if (textField == self.pwdTf) {
        if (textField.text.length > 15) {
            textField.text = [textField.text substringToIndex:15];
        }
    }

    if (textField == self.codeTf) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }

}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wxLogin" object:nil];
}

- (void) signInWithApple {

    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *request = [provider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *vc = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        vc.delegate = self;
        vc.presentationContextProvider = self;
        [vc performRequests];
    }
}


- (void) appleLoginWithParams:(NSMutableDictionary *)params {
    NSString *url = @"/api/tiny-shop/v1/third-party/apple";
    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:url params:params successBlock:^(NSDictionary * _Nonnull response) {
        NSDictionary *data = response[@"data"];
        if ([data[@"login"] intValue] == 1) { //登录信息

            //使用归档保存数据
            LoginModel *model = [LoginModel mj_objectWithKeyValues:data[@"user_info"]];
            [[UserAccountManager shared] saveUser:model];
//            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsSalesMan];
//            [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];


            [JPushFunc pushJPushRegisterID];
            [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        } else {//授权信息
//            WxBindPhoneVC *vc = [[WxBindPhoneVC alloc] init];
//            vc.authDic = data[@"user_info"];
//            vc.type = 1;
//            [self.navigationController pushViewController:vc animated:YES];
        }
    } failureBlock:^(NSError * _Nonnull error) {

    }];
}

////苹果注册
//- (void) appleCreateWithWithUserID:(NSString *)userid nickname:(NSString *)nickname {
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"oauth_client"] = @"apple";
//    params[@"oauth_client_user_id"] = userid;
//
//    params[@"nickname"] = nickname;
//
//
//    [[NetWorksTools shared] requestWithMethod:POST url:@"/api/tiny-shop/v1/member/auth/create" params:params successBlock:^(NSDictionary * _Nonnull response) {
//
//        //登录成功
//        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsSalesMan];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];
//
//        //登录成功
//        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//    } failureBlock:^(NSError * _Nonnull error) {
//
//        WxBindPhoneVC *vc = [[WxBindPhoneVC alloc] init];
//        vc.authDic = data[@"user_info"];
//
//        [self.navigationController pushViewController:vc animated:YES];
//
//    }];
//}


#pragma mark - ASAuthorizationControllerDelegate

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    NSLog(@"%@", errorMsg);
}


//完成apple账号验证
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {

    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        NSString *state = credential.state;
        NSString *userID = credential.user;
        NSPersonNameComponents *fullName = credential.fullName;
        NSString *email = credential.email;
        NSString *authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
        NSString *identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        NSArray *authorizedScopes = credential.authorizedScopes;

        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"user"] = userID;
        params[@"identityToken"] = identityToken;
        params[@"email"] = email;
        params[@"authorizationCode"] = authorizationCode;
        params[@"fullName"] = [NSString stringWithFormat:@"%@%@", fullName.familyName ? fullName.familyName : @"", fullName.givenName? fullName.givenName : @""];
        params[@"user"] = userID;
        params[@"user"] = userID;
        params[@"user"] = userID;

        NSLog(@"state: %@", state);
        NSLog(@"userID: %@", userID);
        NSLog(@"fullName: %@", fullName);
        NSLog(@"email: %@", email);
        NSLog(@"authorizationCode: %@", authorizationCode);
        NSLog(@"identityToken: %@", identityToken);
        NSLog(@"realUserStatus: %@", @(realUserStatus));
        NSLog(@"authorizedScopes: %@", authorizedScopes);

        [self appleLoginWithParams:params];
    }
}

#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)) {
    return [UIApplication sharedApplication].keyWindow;
}
- (NSString *)documentPath{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return documentPath;
}
@end
